<?php
namespace Home\Controller;
use function MongoDB\BSON\toJSON;
use Think\Controller;
class InterController extends Controller {

    //获取问题列表接口
    public function InterQuestionList()
    {

        $QuestionList = M('question');
        $result = $QuestionList->join('course on course.c_id=question.q_c_id')->order('q_time desc')->select();
        if($result!=false)
        {
/*            for($i = 0; $i < count($result); $i++){
                $result[$i]['q_content'] = htmlspecialchars_decode($result[$i]['q_content']);
            }*/
            $this->ajaxReturn($result,'JSON');
        }
        else{
            $data = array();
            $this->ajaxReturn($data,'JSON');
        }
    }

    //获取问题详情接口
    public function InterQuestionInfo($q_id)
    {

        $QuestionList = M('question');
        $result = $QuestionList->join('course on course.c_id=question.q_c_id')->where("q_id=$q_id")->select();
        if($result)
        {
            $this->ajaxReturn($result['0'],'JSON');
        }
    }

    //获取关注问题列表接口
    public function InterQuestionLike($u_id)
    {

        $QuestionLike = M('questionlike');
        //问题关注表、问题表、用户表 4表链接
        $result = $QuestionLike->join('question on question.q_id=questionlike.ql_q_id')
            ->join('user on user.u_id=questionlike.ql_u_id')
            ->join('course on course.c_id=question.q_c_id')
            ->where("ql_u_id=$u_id")->select();

        if($result)
        {
            $this->ajaxReturn($result,'JSON');
        }else{
            $this->ajaxReturn(array(),'JSON');
        }
    }

    //获取回答列表接口
    public function InterAnswerList($q_id)
    {

        $AnswerList = M('user');
        $result = $AnswerList->join('question on question.q_id=user.an_q_id')
            ->join('user on user.u_id=user.an_u_id')->where("q_id=$q_id")->select();
//        dump($result);
        if($result)
        {
            $this->ajaxReturn($result,'JSON');
        }else{
            $data = array();
            $this->ajaxReturn($data,'JSON');
        }
    }

    //获取回答详情接口
    public function InterAnswerInfo($an_id)
    {

        $AnswerInfo = M('user');
        $result = $AnswerInfo->join('question on question.q_id=user.an_q_id')
            ->join('user on user.u_id=user.an_u_id')->
            where("an_id=$an_id")->select();
        if($result) {
            $this->ajaxReturn($result['0'],'JSON');
        } else{
            $this->ajaxReturn(array(),'JSON');
        }
    }


    //判断某人是否关注某问题
    public function isLikeProblem($uid,$qid){
        $Questionlike = M('questionlike');

        if( $Questionlike->where("ql_q_id=$qid AND ql_u_id=$uid")->select() ){
            $data = array('res' => 'yes');
            $this->ajaxReturn($data,'JSON');
        }else{
            $data = array('res' => 'no');
            $this->ajaxReturn($data,'JSON');
        }

    }

    //收藏回答
    public function likeAnswerById($uid,$aid){
        $data['al_an_id'] = $aid;
        $data['al_u_id'] = $uid;

        //answerlike表添加字段
        $AnswerLike = M('answerlike');
        if($AnswerLike->add($data)){

            //answer表q_like_num + 1
            $Answer = M('user');
            $res = ($Answer->where("an_id=$aid")->select());

            $anLikeNum = $res['0']['an_like_num'];
            $anLikeNum = $anLikeNum+1;

            $update['an_like_num'] = $anLikeNum;
            if($Answer->where("an_id=$aid")->save($update)){
                $data = array('res' => 'success');
                $this->ajaxReturn($data,'JSON');
            }else{
                $data = array('res' => 'failure');
                $this->ajaxReturn($data,'JSON');
            }
        }else{
            $data = array('res' => 'failure');
            $this->ajaxReturn($data,'JSON');
        }
    }


    //取消收藏回答
    public function cancelLikeAnswer($uid,$aid){

        $AnswerLike = M('answerlike');
        if($AnswerLike->where("al_an_id=$aid AND al_u_id=$uid")->delete()){

            //answer表an_like_num - 1
            $Answer = M('user');
            $res = $Answer->where("an_id=$aid")->select();
            $anLikeNum = $res['0']['an_like_num'] - 1;

            $update['an_like_num'] = $anLikeNum;
            if($Answer->where("an_id=$aid")->save($update)){
                $data = array('res' => 'success');
                $this->ajaxReturn($data,'JSON');
            }else{
                $data = array('res' => 'failure');
                $this->ajaxReturn($data,'JSON');
            }
        }else{
            $data = array('res' => 'failure');
            $this->ajaxReturn($data,'JSON');
        }
    }

    //判断某人是否收藏某回答
    public function isLikeAnswer($uid,$aid){
        $answerlike = M('answerlike');

        if( $answerlike->where("al_an_id=$aid AND al_u_id=$uid")->select() ){
            $data = array('res' => 'yes');
            $this->ajaxReturn($data,'JSON');
        }else{
            $data = array('res' => 'no');
            $this->ajaxReturn($data,'JSON');
        }

    }


    //获取收藏回答列表接口
    public function InterAnswerLike($u_id)
    {

        $AnswerLike = M('answerlike');
        //收藏回答表、回答表、用户表 三表链接
        $result = $AnswerLike->join('user on user.an_id=answerlike.al_an_id')
            ->join('user on user.u_id=answerlike.al_u_id')
            ->join('question on question.q_id=user.an_q_id')->where("al_u_id=$u_id")->select();
        if($result)
        {
            $this->ajaxReturn($result,'JSON');
        }
        else{
            $this->ajaxReturn(array(),'JSON');
        }
    }

    //登陆接口
    public function InterLogin($userphone,$password)
    {
        $userModel=M('user');
        $where['u_phone']  = array('eq', $userphone);//$map['字段名'] = array('表达式','查询条件'); eq表示等于
        $where['u_pwd']  = array('eq',$password);//实际的项目一般密码都会采用MD5算法进行加密
        $result= $userModel->where($where)->find();
        if(empty($result))//如果找不到数据
        {
            $data = array('u_id' => '0','u_state' => '0' );
            $this->ajaxReturn($data,'JSON');
        }
        else
        {
//            dump($result);
            $data = array('u_id' => $result['u_id'],'u_state' => $result['u_state']  );
            $this->ajaxReturn($data,'JSON');
        }
    }

    //注册接口
    public function InterReg($userphone,$password)
    {
        $user = M("user");

        $data1['u_phone'] = $userphone;
        $data1['u_pwd'] = $password;
        $data1['u_name'] = "a".$userphone;
        $data1['u_time'] = date('Y-m-d H:i:s',time());;

        $where['u_phone'] = $userphone;

        if($user->where($where)->select() != NULL){ //查重
            $data = array('u_id' => '-1');
            $this->ajaxReturn($data,'JSON');
        }else if ($res = $user->add($data1)) { //注册成功
            $data = array('u_id' => $res);
            $this->ajaxReturn($data,'JSON');
        } else { //注册失败
            $data = array('u_id' => '0');
            $this->ajaxReturn($data,'JSON');
        }

    }


    //获取所有课程列表
    public function GetAllCourse(){
        $Course = M('course');

        $courseList = $Course->select();
        $this->ajaxReturn($courseList,'JSON');
    }
    

    //提问接口
    //$title,$content,$uid,$pic,$time,$cid
    public function AskQuestion(){ //type = 0 问题相关图 type = 1回答相关图 type = 2 用户头像
        $title = str_replace('"','', $_POST['title']);
        $content = str_replace('"','', $_POST['content']);
//        $title = I('post.title',false);
//        $content = I('post.content',false);
        $uid = I('post.uid');
        $time = date("Y-m-d H:i:s");
        $cid = I('post.cid');
        $type = $_POST['type'];

        $pname = null;

        $Question = M("question");

        if(!empty($_FILES['file']['tmp_name'])){ //如果有图片上传
            if($_FILES['file']['error'] == 0){ //上传了文件
                if ($picinfo = $this->upload($type)) { //上传成功
                    $pname = $picinfo['file']['savename'];
                }
            }
        }

        $data['q_title'] = $title;
        $data['q_content'] = $content;
        $data['q_u_id'] = $uid;
        $data['q_pic'] = $pname;
        $data['q_time'] = $time;
        $data['q_c_id'] = $cid;

        if($Question->add($data)){
            $data = array('res' => 'success');
            $this->ajaxReturn($data,'JSON');
        }else{
            $data = array('res' => 'failure');
            $this->ajaxReturn($data,'JSON');
        }
    }


    //回答接口
    //需要接收：qid,uid,content,pic
    public function AnswerQuestion(){ //type = 0 问题相关图 type = 1回答相关图 type = 2 用户头像
        $content = str_replace('"','', $_POST['content']);
        $uid = I('post.uid');
        $qid = I('post.qid');
        $time = date("Y-m-d H:i:s");
        $type = $_POST['type'];

        $pname = null;

        $Answer = M("user");

        if(!empty($_FILES['file']['tmp_name'])){ //如果有图片上传
            if($_FILES['file']['error'] == 0){ //上传了文件
                if ($picinfo = $this->upload($type)) { //上传成功
                    $pname = $picinfo['file']['savename'];
                }
            }
        }

        $data['an_q_id'] = $qid;
        $data['an_u_id'] = $uid;
        $data['an_content'] = $content;
        $data['an_pic'] = $pname;
        $data['an_time'] = $time;

        if($Answer->add($data)){
            $data = array('res' => 'success');
            $this->ajaxReturn($data,'JSON');
        }else{
            $data = array('res' => 'failure');
            $this->ajaxReturn($data,'JSON');
        }
    }




    //关注问题接口
    public function likeProblemById($uid,$qid){
        $data['ql_q_id'] = $qid;
        $data['ql_u_id'] = $uid;

        //questionlike表添加字段
        $QuestionList = M('questionlike');
        if($QuestionList->add($data)){

            //question表q_like_num + 1
            $Question = M('question');
            $res = ($Question->where("q_id=$qid")->select());

            $qLikeNum = $res['0']['q_like_num'];
            $qLikeNum = $qLikeNum+1;
            $qid = $res['0']['q_id'];

            $update['q_like_num'] = $qLikeNum;
            if($Question->where("q_id=$qid")->save($update)){
                $data = array('res' => 'success');
                $this->ajaxReturn($data,'JSON');
            }else{
                $data = array('res' => 'failure');
                $this->ajaxReturn($data,'JSON');
            }
        }else{
            $data = array('res' => 'failure');
            $this->ajaxReturn($data,'JSON');
        }
    }

    //取消关注问题接口
    public function cancelLikeProblem($uid,$qid){

        $QuestionLike = M('questionlike');
        if($QuestionLike->where("ql_q_id=$qid AND ql_u_id=$uid")->delete()){

            //question表q_like_num - 1
            $Question = M('question');
            $res = $Question->where("q_id=$qid")->select();
            $qLikeNum = $res['0']['q_like_num'] - 1;

            $update['q_like_num'] = $qLikeNum;
            if($Question->where("q_id=$qid")->save($update)){
                $data = array('res' => 'success');
                $this->ajaxReturn($data,'JSON');
            }else{
                $data = array('res' => 'failure');
                $this->ajaxReturn($data,'JSON');
            }
        }else{
            $data = array('res' => 'failure');
            $this->ajaxReturn($data,'JSON');
        }
    }


    //搜索接口（模糊搜索问题标题+问题Content
    public function search($key){
        $Question = M('question');
        $res = $Question->join('course on course.c_id=question.q_c_id')->where("q_title like '%$key%' or q_content like '%$key%'")->select();
        if($res){
            $this->ajaxReturn($res,'JSON');
        }else{
            $this->ajaxReturn(array(),'JSON');
        }
    }

    //按课程分类显示课程问题接口
    public function getQuestionlistByCid($cid){
        $Question = M('question');
        $res = $Question->join('course on course.c_id=question.q_c_id')->where("q_c_id=$cid")->select();
        if($res){
            $this->ajaxReturn($res,'JSON');
        }else{
            $this->ajaxReturn(array(),'JSON');
        }
    }

    //获取用户信息接口
    public function getUserInfo($uid){
        $User = M('user');
        $res = $User->select($uid);
        if($res){
            $this->ajaxReturn($res['0'],'JSON');
        }else{
            $this->ajaxReturn(null,'JSON');
        }
    }

    //获取某用户关注问题数目
    public function getUserLikeQuestionNum($uid){
        $QuestionLike = M('questionlike');
        $res = $QuestionLike->where("ql_u_id=$uid")->count();

        $data = array('count' => $res);
        $this->ajaxReturn($data);
    }

    //获取某用户收藏回答数目
    public function getUserLikeAnswerNum($uid){
        $AnswerLike = M('answerlike');
        $res = $AnswerLike->where("al_u_id=$uid")->count();

        $data = array('count' => $res);
        $this->ajaxReturn($data);
    }

    //获取某用户提出的问题数目
    public function getUserAskQuestionNum($uid){
        $Question = M('question');
        $res = $Question->where("q_u_id=$uid")->count();

        $data = array('count' => $res);
        $this->ajaxReturn($data);
    }

    //获取某用户回答的问题数目
    public function getUserAnswerQuestionNum($uid){
        $Answer = M('user');
        $res = $Answer->where("an_u_id=$uid")->count();

        $data = array('count' => $res);
        $this->ajaxReturn($data);
    }

    //获取某个用户的回答列表
    public function getMyAnswerList($uid){
        $Answer = M('user');
        $result = $Answer->join('question on question.q_id=user.an_q_id')
            ->join('user on user.u_id=user.an_u_id')->where("an_u_id=$uid")->select();
//        dump($result);
        if($result)
        {
            $this->ajaxReturn($result,'JSON');
        }else{
            $data = array();
            $this->ajaxReturn($data,'JSON');
        }
    }

    //获取某个用户的提问列表
        public function getMyQuestionList($uid){
        $Answer = M('question');
        $result = $Answer->join('user on user.an_q_id=question.q_id')
            ->join('user on user.u_id=question.q_u_id')
            ->join('course on course.c_id=q_c_id')->where("q_u_id=$uid")->select();
//        dump($result);
        if($result)
        {
            $this->ajaxReturn($result,'JSON');
        }else{
            $data = array();
            $this->ajaxReturn($data,'JSON');
        }
    }

    //修改用户信息（用户名、个人简介）
    public function doModifyUserInfo($uid,$uname,$uintro){
        $User = M('user');

        $data['u_name'] = $uname;
        $data['u_intro'] = $uintro;
        $res = $User->where("u_id=$uid")->save($data); // 根据条件更新记录

        if($res){
            $data = array('res' => 'success');
            $this->ajaxReturn($data);
        }else{
            $data = array('res' => 'failure');
            $this->ajaxReturn($data);
        }
    }

    //测试上传图片(测试！测试！测试！)
    public function uploadImg(){ //type = 0 问题相关图 type = 1回答相关图 type = 2 用户头像

        $type = $_POST['type'];
        $test = $_POST['test'];

        $pname = "123";
        if(!empty($_FILES['file']['tmp_name'])){ //如果有文件上传
            if($_FILES['file']['error'] == 0){ //上传了文件并且通过服务器关卡
                if ($picinfo = $this->upload($type)) { //上传成功
                    $pname = $picinfo['files']['savename'];
                    $this->ajaxReturn($pname);
                }else{ //上传失败
//                $data = array('filename' => '-1');
                    $this->ajaxReturn('-1');
                }
            }else{ //没有上传文件
//            $data = array('filename' => '0');
                $this->ajaxReturn('0');
            }
        }

        $Test = M('test');
        $data['filename'] = $pname;
        $data['test'] = $test;
        dump($data);
        if($Test->add($data)){
            $this->ajaxReturn('1000');
        }else{
            $this->ajaxReturn('999');
        }

    }

    //上传文件参考
    public function upload($type){ //type含义同uploadImg方法

        switch ($type){
            case 0:
                $imgSavePath = './Public/upload/questionpics/';
                break;
            case 1:
                $imgSavePath = './Public/upload/answerpics/';
                break;
            case 2:
                $imgSavePath = './Public/upload/userpics/';
                break;
            default:
                $imgSavePath = './Public/upload/otherpics/';
                break;
        }

        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize = 3145728;// 设置附件上传大小
        $upload->exts = array('jpg','jpeg','png');// 设置附件上传类型
        $upload->rootPath = $imgSavePath; // 设置附件上传根目录
        $upload->savePath = ''; // 设置附件上传（子）目录
        $upload->autoSub = false;
        $upload->saveName = time() . mt_rand(); //实际保存文件名：时间戳+随机数
        // 上传文件
        $info = $upload->upload();
        if (!$info) {// 上传错误提示错误信息
            $this->error($upload->getError());
        } else {// 上传成功
            return $info;
        }
    }

    //设置某用户喜欢的课程
    public function setUserLikeCourse(){ //用户id， 用户喜欢的课程id数组
        $uid = $_GET['uid'];
        $cidArr = $_GET['cid'];

        $CourseLike = M('courselike');

        if($CourseLike->where("cl_u_id=$uid")->delete() !== false){ //先删掉该用户原来喜欢的课程
            //保存新的喜欢课程
            for($i = 0; $i < sizeof($cidArr); $i++){ //构造插入数据
                $dataList[] = array('cl_u_id'=>$uid,'cl_c_id'=>$cidArr[$i]);
            }
            if($result = $CourseLike->addAll($dataList)){
                $res = array('res'=>'success');
                $this->ajaxReturn($res);
            }else{
                $res = array('res'=>"failure"); //添加新数据失败
                $this->ajaxReturn($res);
            }
        }else{
            $res = array('res'=>"failure-1"); //删除原有数据失败
            $this->ajaxReturn($res);
        }
    }

    //查询某用户喜欢的课程相关问题
    public function getUserLikeCourseQuestion($uid){
        $Courselike = M('courselike');
        $cid = $Courselike->where("cl_u_id=$uid")->getField('cl_c_id',true);

        $Course = M('course');
        //用查询结果查询
        //用查询出来的cid查询该课程下的问题
        $res = $Courselike->join("question on question.q_c_id = cl_c_id")
            ->join("course on course.c_id = cl_c_id")
            ->where(array('cl_c_id'=>array('in',$cid)))->order('q_time desc')->select();//->getField('c_id,c_name',true);

        $this->ajaxReturn($res);
    }
}